3 * MediaWiki page data importer.
5 * Copyright © 2003,2005 Brion Vibber <brion@pobox.com>
6 * https://www.mediawiki.org/
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
24 * @ingroup SpecialPage
28 * XML file reader for the page data importer
30 * implements Special:Import
31 * @ingroup SpecialPage
34 private $reader = null;
35 private $foreignNamespaces = null;
36 private $mLogItemCallback, $mUploadCallback, $mRevisionCallback, $mPageCallback;
37 private $mSiteInfoCallback, $mTargetNamespace, $mPageOutCallback;
38 private $mNoticeCallback, $mDebug;
39 private $mImportUploads, $mImageBasePath;
40 private $mNoUpdates = false;
43 /** @var ImportTitleFactory */
44 private $importTitleFactory;
47 * Creates an ImportXMLReader drawing from the source provided
48 * @param ImportSource $source
49 * @param Config $config
51 function __construct( ImportSource
$source, Config
$config = null ) {
52 $this->reader
= new XMLReader();
54 wfDeprecated( __METHOD__
. ' without a Config instance', '1.25' );
55 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
57 $this->config
= $config;
59 if ( !in_array( 'uploadsource', stream_get_wrappers() ) ) {
60 stream_wrapper_register( 'uploadsource', 'UploadSourceAdapter' );
62 $id = UploadSourceAdapter
::registerSource( $source );
63 if ( defined( 'LIBXML_PARSEHUGE' ) ) {
64 $this->reader
->open( "uploadsource://$id", null, LIBXML_PARSEHUGE
);
66 $this->reader
->open( "uploadsource://$id" );
70 $this->setRevisionCallback( array( $this, "importRevision" ) );
71 $this->setUploadCallback( array( $this, 'importUpload' ) );
72 $this->setLogItemCallback( array( $this, 'importLogItem' ) );
73 $this->setPageOutCallback( array( $this, 'finishImportPage' ) );
75 $this->importTitleFactory
= new NaiveImportTitleFactory();
79 * @return null|XMLReader
81 public function getReader() {
85 public function throwXmlError( $err ) {
86 $this->debug( "FAILURE: $err" );
87 wfDebug( "WikiImporter XML error: $err\n" );
90 public function debug( $data ) {
91 if ( $this->mDebug
) {
92 wfDebug( "IMPORT: $data\n" );
96 public function warn( $data ) {
97 wfDebug( "IMPORT: $data\n" );
100 public function notice( $msg /*, $param, ...*/ ) {
101 $params = func_get_args();
102 array_shift( $params );
104 if ( is_callable( $this->mNoticeCallback
) ) {
105 call_user_func( $this->mNoticeCallback
, $msg, $params );
106 } else { # No ImportReporter -> CLI
107 echo wfMessage( $msg, $params )->text() . "\n";
115 function setDebug( $debug ) {
116 $this->mDebug
= $debug;
120 * Set 'no updates' mode. In this mode, the link tables will not be updated by the importer
121 * @param bool $noupdates
123 function setNoUpdates( $noupdates ) {
124 $this->mNoUpdates
= $noupdates;
128 * Set a callback that displays notice messages
130 * @param callable $callback
133 public function setNoticeCallback( $callback ) {
134 return wfSetVar( $this->mNoticeCallback
, $callback );
138 * Sets the action to perform as each new page in the stream is reached.
139 * @param callable $callback
142 public function setPageCallback( $callback ) {
143 $previous = $this->mPageCallback
;
144 $this->mPageCallback
= $callback;
149 * Sets the action to perform as each page in the stream is completed.
150 * Callback accepts the page title (as a Title object), a second object
151 * with the original title form (in case it's been overridden into a
152 * local namespace), and a count of revisions.
154 * @param callable $callback
157 public function setPageOutCallback( $callback ) {
158 $previous = $this->mPageOutCallback
;
159 $this->mPageOutCallback
= $callback;
164 * Sets the action to perform as each page revision is reached.
165 * @param callable $callback
168 public function setRevisionCallback( $callback ) {
169 $previous = $this->mRevisionCallback
;
170 $this->mRevisionCallback
= $callback;
175 * Sets the action to perform as each file upload version is reached.
176 * @param callable $callback
179 public function setUploadCallback( $callback ) {
180 $previous = $this->mUploadCallback
;
181 $this->mUploadCallback
= $callback;
186 * Sets the action to perform as each log item reached.
187 * @param callable $callback
190 public function setLogItemCallback( $callback ) {
191 $previous = $this->mLogItemCallback
;
192 $this->mLogItemCallback
= $callback;
197 * Sets the action to perform when site info is encountered
198 * @param callable $callback
201 public function setSiteInfoCallback( $callback ) {
202 $previous = $this->mSiteInfoCallback
;
203 $this->mSiteInfoCallback
= $callback;
208 * Sets the factory object to use to convert ForeignTitle objects into local
210 * @param ImportTitleFactory $factory
212 public function setImportTitleFactory( $factory ) {
213 $this->importTitleFactory
= $factory;
217 * Set a target namespace to override the defaults
218 * @param null|int $namespace
221 public function setTargetNamespace( $namespace ) {
222 if ( is_null( $namespace ) ) {
223 // Don't override namespaces
224 $this->mTargetNamespace
= null;
225 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
229 MWNamespace
::exists( intval( $namespace ) )
231 $namespace = intval( $namespace );
232 $this->mTargetNamespace
= $namespace;
233 $this->setImportTitleFactory( new NamespaceImportTitleFactory( $namespace ) );
241 * Set a target root page under which all pages are imported
242 * @param null|string $rootpage
245 public function setTargetRootPage( $rootpage ) {
246 $status = Status
::newGood();
247 if ( is_null( $rootpage ) ) {
249 $this->setImportTitleFactory( new NaiveImportTitleFactory() );
250 } elseif ( $rootpage !== '' ) {
251 $rootpage = rtrim( $rootpage, '/' ); //avoid double slashes
252 $title = Title
::newFromText( $rootpage, !is_null( $this->mTargetNamespace
)
253 ?
$this->mTargetNamespace
257 if ( !$title ||
$title->isExternal() ) {
258 $status->fatal( 'import-rootpage-invalid' );
260 if ( !MWNamespace
::hasSubpages( $title->getNamespace() ) ) {
263 $displayNSText = $title->getNamespace() == NS_MAIN
264 ?
wfMessage( 'blanknamespace' )->text()
265 : $wgContLang->getNsText( $title->getNamespace() );
266 $status->fatal( 'import-rootpage-nosubpage', $displayNSText );
268 // set namespace to 'all', so the namespace check in processTitle() can pass
269 $this->setTargetNamespace( null );
270 $this->setImportTitleFactory( new SubpageImportTitleFactory( $title ) );
280 public function setImageBasePath( $dir ) {
281 $this->mImageBasePath
= $dir;
285 * @param bool $import
287 public function setImportUploads( $import ) {
288 $this->mImportUploads
= $import;
292 * Default per-revision callback, performs the import.
293 * @param WikiRevision $revision
296 public function importRevision( $revision ) {
297 if ( !$revision->getContentHandler()->canBeUsedOn( $revision->getTitle() ) ) {
298 $this->notice( 'import-error-bad-location',
299 $revision->getTitle()->getPrefixedText(),
301 $revision->getModel(),
302 $revision->getFormat() );
308 $dbw = wfGetDB( DB_MASTER
);
309 return $dbw->deadlockLoop( array( $revision, 'importOldRevision' ) );
310 } catch ( MWContentSerializationException
$ex ) {
311 $this->notice( 'import-error-unserialize',
312 $revision->getTitle()->getPrefixedText(),
314 $revision->getModel(),
315 $revision->getFormat() );
322 * Default per-revision callback, performs the import.
323 * @param WikiRevision $revision
326 public function importLogItem( $revision ) {
327 $dbw = wfGetDB( DB_MASTER
);
328 return $dbw->deadlockLoop( array( $revision, 'importLogItem' ) );
333 * @param WikiRevision $revision
336 public function importUpload( $revision ) {
337 $dbw = wfGetDB( DB_MASTER
);
338 return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
342 * Mostly for hook use
343 * @param Title $title
344 * @param ForeignTitle $foreignTitle
345 * @param int $revCount
346 * @param int $sRevCount
347 * @param array $pageInfo
350 public function finishImportPage( $title, $foreignTitle, $revCount,
351 $sRevCount, $pageInfo ) {
352 $args = func_get_args();
353 return Hooks
::run( 'AfterImportPage', $args );
357 * Alternate per-revision callback, for debugging.
358 * @param WikiRevision $revision
360 public function debugRevisionHandler( &$revision ) {
361 $this->debug( "Got revision:" );
362 if ( is_object( $revision->title
) ) {
363 $this->debug( "-- Title: " . $revision->title
->getPrefixedText() );
365 $this->debug( "-- Title: <invalid>" );
367 $this->debug( "-- User: " . $revision->user_text
);
368 $this->debug( "-- Timestamp: " . $revision->timestamp
);
369 $this->debug( "-- Comment: " . $revision->comment
);
370 $this->debug( "-- Text: " . $revision->text
);
374 * Notify the callback function of site info
375 * @param array $siteInfo
378 private function siteInfoCallback( $siteInfo ) {
379 if ( isset( $this->mSiteInfoCallback
) ) {
380 return call_user_func_array( $this->mSiteInfoCallback
,
381 array( $siteInfo, $this ) );
388 * Notify the callback function when a new "<page>" is reached.
389 * @param Title $title
391 function pageCallback( $title ) {
392 if ( isset( $this->mPageCallback
) ) {
393 call_user_func( $this->mPageCallback
, $title );
398 * Notify the callback function when a "</page>" is closed.
399 * @param Title $title
400 * @param ForeignTitle $foreignTitle
401 * @param int $revCount
402 * @param int $sucCount Number of revisions for which callback returned true
403 * @param array $pageInfo Associative array of page information
405 private function pageOutCallback( $title, $foreignTitle, $revCount,
406 $sucCount, $pageInfo ) {
407 if ( isset( $this->mPageOutCallback
) ) {
408 $args = func_get_args();
409 call_user_func_array( $this->mPageOutCallback
, $args );
414 * Notify the callback function of a revision
415 * @param WikiRevision $revision
418 private function revisionCallback( $revision ) {
419 if ( isset( $this->mRevisionCallback
) ) {
420 return call_user_func_array( $this->mRevisionCallback
,
421 array( $revision, $this ) );
428 * Notify the callback function of a new log item
429 * @param WikiRevision $revision
432 private function logItemCallback( $revision ) {
433 if ( isset( $this->mLogItemCallback
) ) {
434 return call_user_func_array( $this->mLogItemCallback
,
435 array( $revision, $this ) );
442 * Retrieves the contents of the named attribute of the current element.
443 * @param string $attr The name of the attribute
444 * @return string The value of the attribute or an empty string if it is not set in the current element.
446 public function nodeAttribute( $attr ) {
447 return $this->reader
->getAttribute( $attr );
451 * Shouldn't something like this be built-in to XMLReader?
452 * Fetches text contents of the current element, assuming
453 * no sub-elements or such scary things.
457 public function nodeContents() {
458 if ( $this->reader
->isEmptyElement
) {
462 while ( $this->reader
->read() ) {
463 switch ( $this->reader
->nodeType
) {
464 case XMLReader
::TEXT
:
465 case XMLReader
::SIGNIFICANT_WHITESPACE
:
466 $buffer .= $this->reader
->value
;
468 case XMLReader
::END_ELEMENT
:
473 $this->reader
->close();
478 * Primary entry point
479 * @throws MWException
482 public function doImport() {
483 // Calls to reader->read need to be wrapped in calls to
484 // libxml_disable_entity_loader() to avoid local file
485 // inclusion attacks (bug 46932).
486 $oldDisable = libxml_disable_entity_loader( true );
487 $this->reader
->read();
489 if ( $this->reader
->name
!= 'mediawiki' ) {
490 libxml_disable_entity_loader( $oldDisable );
491 throw new MWException( "Expected <mediawiki> tag, got " .
492 $this->reader
->name
);
494 $this->debug( "<mediawiki> tag is correct." );
496 $this->debug( "Starting primary dump processing loop." );
498 $keepReading = $this->reader
->read();
502 while ( $keepReading ) {
503 $tag = $this->reader
->name
;
504 $type = $this->reader
->nodeType
;
506 if ( !Hooks
::run( 'ImportHandleToplevelXMLTag', array( $this ) ) ) {
508 } elseif ( $tag == 'mediawiki' && $type == XMLReader
::END_ELEMENT
) {
510 } elseif ( $tag == 'siteinfo' ) {
511 $this->handleSiteInfo();
512 } elseif ( $tag == 'page' ) {
514 } elseif ( $tag == 'logitem' ) {
515 $this->handleLogItem();
516 } elseif ( $tag != '#text' ) {
517 $this->warn( "Unhandled top-level XML tag $tag" );
523 $keepReading = $this->reader
->next();
525 $this->debug( "Skip" );
527 $keepReading = $this->reader
->read();
530 } catch ( Exception
$ex ) {
535 libxml_disable_entity_loader( $oldDisable );
536 $this->reader
->close();
545 private function handleSiteInfo() {
546 $this->debug( "Enter site info handler." );
549 // Fields that can just be stuffed in the siteInfo object
550 $normalFields = array( 'sitename', 'base', 'generator', 'case' );
552 while ( $this->reader
->read() ) {
553 if ( $this->reader
->nodeType
== XmlReader
::END_ELEMENT
&&
554 $this->reader
->name
== 'siteinfo' ) {
558 $tag = $this->reader
->name
;
560 if ( $tag == 'namespace' ) {
561 $this->foreignNamespaces
[ $this->nodeAttribute( 'key' ) ] =
562 $this->nodeContents();
563 } elseif ( in_array( $tag, $normalFields ) ) {
564 $siteInfo[$tag] = $this->nodeContents();
568 $siteInfo['_namespaces'] = $this->foreignNamespaces
;
569 $this->siteInfoCallback( $siteInfo );
572 private function handleLogItem() {
573 $this->debug( "Enter log item handler." );
576 // Fields that can just be stuffed in the pageInfo object
577 $normalFields = array( 'id', 'comment', 'type', 'action', 'timestamp',
578 'logtitle', 'params' );
580 while ( $this->reader
->read() ) {
581 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
582 $this->reader
->name
== 'logitem' ) {
586 $tag = $this->reader
->name
;
588 if ( !Hooks
::run( 'ImportHandleLogItemXMLTag', array(
592 } elseif ( in_array( $tag, $normalFields ) ) {
593 $logInfo[$tag] = $this->nodeContents();
594 } elseif ( $tag == 'contributor' ) {
595 $logInfo['contributor'] = $this->handleContributor();
596 } elseif ( $tag != '#text' ) {
597 $this->warn( "Unhandled log-item XML tag $tag" );
601 $this->processLogItem( $logInfo );
605 * @param array $logInfo
608 private function processLogItem( $logInfo ) {
609 $revision = new WikiRevision( $this->config
);
611 $revision->setID( $logInfo['id'] );
612 $revision->setType( $logInfo['type'] );
613 $revision->setAction( $logInfo['action'] );
614 $revision->setTimestamp( $logInfo['timestamp'] );
615 $revision->setParams( $logInfo['params'] );
616 $revision->setTitle( Title
::newFromText( $logInfo['logtitle'] ) );
617 $revision->setNoUpdates( $this->mNoUpdates
);
619 if ( isset( $logInfo['comment'] ) ) {
620 $revision->setComment( $logInfo['comment'] );
623 if ( isset( $logInfo['contributor']['ip'] ) ) {
624 $revision->setUserIP( $logInfo['contributor']['ip'] );
626 if ( isset( $logInfo['contributor']['username'] ) ) {
627 $revision->setUserName( $logInfo['contributor']['username'] );
630 return $this->logItemCallback( $revision );
633 private function handlePage() {
635 $this->debug( "Enter page handler." );
636 $pageInfo = array( 'revisionCount' => 0, 'successfulRevisionCount' => 0 );
638 // Fields that can just be stuffed in the pageInfo object
639 $normalFields = array( 'title', 'ns', 'id', 'redirect', 'restrictions' );
644 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
645 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
646 $this->reader
->name
== 'page' ) {
652 $tag = $this->reader
->name
;
655 // The title is invalid, bail out of this page
657 } elseif ( !Hooks
::run( 'ImportHandlePageXMLTag', array( $this,
660 } elseif ( in_array( $tag, $normalFields ) ) {
664 // <title>Page</title>
665 // <redirect title="NewTitle"/>
667 // Because the redirect tag is built differently, we need special handling for that case.
668 if ( $tag == 'redirect' ) {
669 $pageInfo[$tag] = $this->nodeAttribute( 'title' );
671 $pageInfo[$tag] = $this->nodeContents();
673 } elseif ( $tag == 'revision' ||
$tag == 'upload' ) {
674 if ( !isset( $title ) ) {
675 $title = $this->processTitle( $pageInfo['title'],
676 isset( $pageInfo['ns'] ) ?
$pageInfo['ns'] : null );
683 $this->pageCallback( $title );
684 list( $pageInfo['_title'], $foreignTitle ) = $title;
688 if ( $tag == 'revision' ) {
689 $this->handleRevision( $pageInfo );
691 $this->handleUpload( $pageInfo );
694 } elseif ( $tag != '#text' ) {
695 $this->warn( "Unhandled page XML tag $tag" );
700 $this->pageOutCallback( $pageInfo['_title'], $foreignTitle,
701 $pageInfo['revisionCount'],
702 $pageInfo['successfulRevisionCount'],
707 * @param array $pageInfo
709 private function handleRevision( &$pageInfo ) {
710 $this->debug( "Enter revision handler" );
711 $revisionInfo = array();
713 $normalFields = array( 'id', 'timestamp', 'comment', 'minor', 'model', 'format', 'text' );
717 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
718 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
719 $this->reader
->name
== 'revision' ) {
723 $tag = $this->reader
->name
;
725 if ( !Hooks
::run( 'ImportHandleRevisionXMLTag', array(
726 $this, $pageInfo, $revisionInfo
729 } elseif ( in_array( $tag, $normalFields ) ) {
730 $revisionInfo[$tag] = $this->nodeContents();
731 } elseif ( $tag == 'contributor' ) {
732 $revisionInfo['contributor'] = $this->handleContributor();
733 } elseif ( $tag != '#text' ) {
734 $this->warn( "Unhandled revision XML tag $tag" );
739 $pageInfo['revisionCount']++
;
740 if ( $this->processRevision( $pageInfo, $revisionInfo ) ) {
741 $pageInfo['successfulRevisionCount']++
;
746 * @param array $pageInfo
747 * @param array $revisionInfo
750 private function processRevision( $pageInfo, $revisionInfo ) {
751 $revision = new WikiRevision( $this->config
);
753 if ( isset( $revisionInfo['id'] ) ) {
754 $revision->setID( $revisionInfo['id'] );
756 if ( isset( $revisionInfo['model'] ) ) {
757 $revision->setModel( $revisionInfo['model'] );
759 if ( isset( $revisionInfo['format'] ) ) {
760 $revision->setFormat( $revisionInfo['format'] );
762 $revision->setTitle( $pageInfo['_title'] );
764 if ( isset( $revisionInfo['text'] ) ) {
765 $handler = $revision->getContentHandler();
766 $text = $handler->importTransform(
767 $revisionInfo['text'],
768 $revision->getFormat() );
770 $revision->setText( $text );
772 if ( isset( $revisionInfo['timestamp'] ) ) {
773 $revision->setTimestamp( $revisionInfo['timestamp'] );
775 $revision->setTimestamp( wfTimestampNow() );
778 if ( isset( $revisionInfo['comment'] ) ) {
779 $revision->setComment( $revisionInfo['comment'] );
782 if ( isset( $revisionInfo['minor'] ) ) {
783 $revision->setMinor( true );
785 if ( isset( $revisionInfo['contributor']['ip'] ) ) {
786 $revision->setUserIP( $revisionInfo['contributor']['ip'] );
788 if ( isset( $revisionInfo['contributor']['username'] ) ) {
789 $revision->setUserName( $revisionInfo['contributor']['username'] );
791 $revision->setNoUpdates( $this->mNoUpdates
);
793 return $this->revisionCallback( $revision );
797 * @param array $pageInfo
800 private function handleUpload( &$pageInfo ) {
801 $this->debug( "Enter upload handler" );
802 $uploadInfo = array();
804 $normalFields = array( 'timestamp', 'comment', 'filename', 'text',
805 'src', 'size', 'sha1base36', 'archivename', 'rel' );
809 while ( $skip ?
$this->reader
->next() : $this->reader
->read() ) {
810 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
811 $this->reader
->name
== 'upload' ) {
815 $tag = $this->reader
->name
;
817 if ( !Hooks
::run( 'ImportHandleUploadXMLTag', array(
821 } elseif ( in_array( $tag, $normalFields ) ) {
822 $uploadInfo[$tag] = $this->nodeContents();
823 } elseif ( $tag == 'contributor' ) {
824 $uploadInfo['contributor'] = $this->handleContributor();
825 } elseif ( $tag == 'contents' ) {
826 $contents = $this->nodeContents();
827 $encoding = $this->reader
->getAttribute( 'encoding' );
828 if ( $encoding === 'base64' ) {
829 $uploadInfo['fileSrc'] = $this->dumpTemp( base64_decode( $contents ) );
830 $uploadInfo['isTempSrc'] = true;
832 } elseif ( $tag != '#text' ) {
833 $this->warn( "Unhandled upload XML tag $tag" );
838 if ( $this->mImageBasePath
&& isset( $uploadInfo['rel'] ) ) {
839 $path = "{$this->mImageBasePath}/{$uploadInfo['rel']}";
840 if ( file_exists( $path ) ) {
841 $uploadInfo['fileSrc'] = $path;
842 $uploadInfo['isTempSrc'] = false;
846 if ( $this->mImportUploads
) {
847 return $this->processUpload( $pageInfo, $uploadInfo );
852 * @param string $contents
855 private function dumpTemp( $contents ) {
856 $filename = tempnam( wfTempDir(), 'importupload' );
857 file_put_contents( $filename, $contents );
862 * @param array $pageInfo
863 * @param array $uploadInfo
866 private function processUpload( $pageInfo, $uploadInfo ) {
867 $revision = new WikiRevision( $this->config
);
868 $text = isset( $uploadInfo['text'] ) ?
$uploadInfo['text'] : '';
870 $revision->setTitle( $pageInfo['_title'] );
871 $revision->setID( $pageInfo['id'] );
872 $revision->setTimestamp( $uploadInfo['timestamp'] );
873 $revision->setText( $text );
874 $revision->setFilename( $uploadInfo['filename'] );
875 if ( isset( $uploadInfo['archivename'] ) ) {
876 $revision->setArchiveName( $uploadInfo['archivename'] );
878 $revision->setSrc( $uploadInfo['src'] );
879 if ( isset( $uploadInfo['fileSrc'] ) ) {
880 $revision->setFileSrc( $uploadInfo['fileSrc'],
881 !empty( $uploadInfo['isTempSrc'] ) );
883 if ( isset( $uploadInfo['sha1base36'] ) ) {
884 $revision->setSha1Base36( $uploadInfo['sha1base36'] );
886 $revision->setSize( intval( $uploadInfo['size'] ) );
887 $revision->setComment( $uploadInfo['comment'] );
889 if ( isset( $uploadInfo['contributor']['ip'] ) ) {
890 $revision->setUserIP( $uploadInfo['contributor']['ip'] );
892 if ( isset( $uploadInfo['contributor']['username'] ) ) {
893 $revision->setUserName( $uploadInfo['contributor']['username'] );
895 $revision->setNoUpdates( $this->mNoUpdates
);
897 return call_user_func( $this->mUploadCallback
, $revision );
903 private function handleContributor() {
904 $fields = array( 'id', 'ip', 'username' );
907 while ( $this->reader
->read() ) {
908 if ( $this->reader
->nodeType
== XMLReader
::END_ELEMENT
&&
909 $this->reader
->name
== 'contributor' ) {
913 $tag = $this->reader
->name
;
915 if ( in_array( $tag, $fields ) ) {
916 $info[$tag] = $this->nodeContents();
924 * @param string $text
925 * @param string|null $ns
928 private function processTitle( $text, $ns = null ) {
929 if ( is_null( $this->foreignNamespaces
) ) {
930 $foreignTitleFactory = new NaiveForeignTitleFactory();
932 $foreignTitleFactory = new NamespaceAwareForeignTitleFactory(
933 $this->foreignNamespaces
);
936 $foreignTitle = $foreignTitleFactory->createForeignTitle( $text,
939 $title = $this->importTitleFactory
->createTitleFromForeignTitle(
942 $commandLineMode = $this->config
->get( 'CommandLineMode' );
943 if ( is_null( $title ) ) {
944 # Invalid page title? Ignore the page
945 $this->notice( 'import-error-invalid', $foreignTitle->getFullText() );
947 } elseif ( $title->isExternal() ) {
948 $this->notice( 'import-error-interwiki', $title->getPrefixedText() );
950 } elseif ( !$title->canExist() ) {
951 $this->notice( 'import-error-special', $title->getPrefixedText() );
953 } elseif ( !$title->userCan( 'edit' ) && !$commandLineMode ) {
954 # Do not import if the importing wiki user cannot edit this page
955 $this->notice( 'import-error-edit', $title->getPrefixedText() );
957 } elseif ( !$title->exists() && !$title->userCan( 'create' ) && !$commandLineMode ) {
958 # Do not import if the importing wiki user cannot create this page
959 $this->notice( 'import-error-create', $title->getPrefixedText() );
963 return array( $title, $foreignTitle );
967 /** This is a horrible hack used to keep source compatibility */
968 class UploadSourceAdapter
{
970 public static $sourceRegistrations = array();
982 * @param ImportSource $source
985 static function registerSource( ImportSource
$source ) {
986 $id = wfRandomString();
988 self
::$sourceRegistrations[$id] = $source;
994 * @param string $path
995 * @param string $mode
996 * @param array $options
997 * @param string $opened_path
1000 function stream_open( $path, $mode, $options, &$opened_path ) {
1001 $url = parse_url( $path );
1004 if ( !isset( self
::$sourceRegistrations[$id] ) ) {
1008 $this->mSource
= self
::$sourceRegistrations[$id];
1017 function stream_read( $count ) {
1021 while ( !$leave && !$this->mSource
->atEnd() &&
1022 strlen( $this->mBuffer
) < $count ) {
1023 $read = $this->mSource
->readChunk();
1025 if ( !strlen( $read ) ) {
1029 $this->mBuffer
.= $read;
1032 if ( strlen( $this->mBuffer
) ) {
1033 $return = substr( $this->mBuffer
, 0, $count );
1034 $this->mBuffer
= substr( $this->mBuffer
, $count );
1037 $this->mPosition +
= strlen( $return );
1043 * @param string $data
1046 function stream_write( $data ) {
1053 function stream_tell() {
1054 return $this->mPosition
;
1060 function stream_eof() {
1061 return $this->mSource
->atEnd();
1067 function url_stat() {
1070 $result['dev'] = $result[0] = 0;
1071 $result['ino'] = $result[1] = 0;
1072 $result['mode'] = $result[2] = 0;
1073 $result['nlink'] = $result[3] = 0;
1074 $result['uid'] = $result[4] = 0;
1075 $result['gid'] = $result[5] = 0;
1076 $result['rdev'] = $result[6] = 0;
1077 $result['size'] = $result[7] = 0;
1078 $result['atime'] = $result[8] = 0;
1079 $result['mtime'] = $result[9] = 0;
1080 $result['ctime'] = $result[10] = 0;
1081 $result['blksize'] = $result[11] = 0;
1082 $result['blocks'] = $result[12] = 0;
1089 * @todo document (e.g. one-sentence class description).
1090 * @ingroup SpecialPage
1092 class WikiRevision
{
1093 /** @todo Unused? */
1094 public $importer = null;
1097 public $title = null;
1103 public $timestamp = "20010115000000";
1107 * @todo Can't find any uses. Public, because that's suspicious. Get clarity. */
1111 public $user_text = "";
1114 public $model = null;
1117 public $format = null;
1126 public $content = null;
1128 /** @var ContentHandler */
1129 protected $contentHandler = null;
1132 public $comment = "";
1135 public $minor = false;
1141 public $action = "";
1144 public $params = "";
1147 public $fileSrc = '';
1149 /** @var bool|string */
1150 public $sha1base36 = false;
1156 public $isTemp = false;
1159 public $archiveName = '';
1161 protected $filename;
1166 /** @todo Unused? */
1170 private $mNoUpdates = false;
1172 /** @var Config $config */
1175 public function __construct( Config
$config ) {
1176 $this->config
= $config;
1180 * @param Title $title
1181 * @throws MWException
1183 function setTitle( $title ) {
1184 if ( is_object( $title ) ) {
1185 $this->title
= $title;
1186 } elseif ( is_null( $title ) ) {
1187 throw new MWException( "WikiRevision given a null title in import. "
1188 . "You may need to adjust \$wgLegalTitleChars." );
1190 throw new MWException( "WikiRevision given non-object title in import." );
1197 function setID( $id ) {
1204 function setTimestamp( $ts ) {
1205 # 2003-08-05T18:30:02Z
1206 $this->timestamp
= wfTimestamp( TS_MW
, $ts );
1210 * @param string $user
1212 function setUsername( $user ) {
1213 $this->user_text
= $user;
1219 function setUserIP( $ip ) {
1220 $this->user_text
= $ip;
1224 * @param string $model
1226 function setModel( $model ) {
1227 $this->model
= $model;
1231 * @param string $format
1233 function setFormat( $format ) {
1234 $this->format
= $format;
1238 * @param string $text
1240 function setText( $text ) {
1241 $this->text
= $text;
1245 * @param string $text
1247 function setComment( $text ) {
1248 $this->comment
= $text;
1252 * @param bool $minor
1254 function setMinor( $minor ) {
1255 $this->minor
= (bool)$minor;
1261 function setSrc( $src ) {
1266 * @param string $src
1267 * @param bool $isTemp
1269 function setFileSrc( $src, $isTemp ) {
1270 $this->fileSrc
= $src;
1271 $this->fileIsTemp
= $isTemp;
1275 * @param string $sha1base36
1277 function setSha1Base36( $sha1base36 ) {
1278 $this->sha1base36
= $sha1base36;
1282 * @param string $filename
1284 function setFilename( $filename ) {
1285 $this->filename
= $filename;
1289 * @param string $archiveName
1291 function setArchiveName( $archiveName ) {
1292 $this->archiveName
= $archiveName;
1298 function setSize( $size ) {
1299 $this->size
= intval( $size );
1303 * @param string $type
1305 function setType( $type ) {
1306 $this->type
= $type;
1310 * @param string $action
1312 function setAction( $action ) {
1313 $this->action
= $action;
1317 * @param array $params
1319 function setParams( $params ) {
1320 $this->params
= $params;
1324 * @param bool $noupdates
1326 public function setNoUpdates( $noupdates ) {
1327 $this->mNoUpdates
= $noupdates;
1333 function getTitle() {
1334 return $this->title
;
1347 function getTimestamp() {
1348 return $this->timestamp
;
1354 function getUser() {
1355 return $this->user_text
;
1361 * @deprecated Since 1.21, use getContent() instead.
1363 function getText() {
1364 ContentHandler
::deprecated( __METHOD__
, '1.21' );
1370 * @return ContentHandler
1372 function getContentHandler() {
1373 if ( is_null( $this->contentHandler
) ) {
1374 $this->contentHandler
= ContentHandler
::getForModelID( $this->getModel() );
1377 return $this->contentHandler
;
1383 function getContent() {
1384 if ( is_null( $this->content
) ) {
1385 $handler = $this->getContentHandler();
1386 $this->content
= $handler->unserializeContent( $this->text
, $this->getFormat() );
1389 return $this->content
;
1395 function getModel() {
1396 if ( is_null( $this->model
) ) {
1397 $this->model
= $this->getTitle()->getContentModel();
1400 return $this->model
;
1406 function getFormat() {
1407 if ( is_null( $this->format
) ) {
1408 $this->format
= $this->getContentHandler()->getDefaultFormat();
1411 return $this->format
;
1417 function getComment() {
1418 return $this->comment
;
1424 function getMinor() {
1425 return $this->minor
;
1436 * @return bool|string
1438 function getSha1() {
1439 if ( $this->sha1base36
) {
1440 return wfBaseConvert( $this->sha1base36
, 36, 16 );
1448 function getFileSrc() {
1449 return $this->fileSrc
;
1455 function isTempSrc() {
1456 return $this->isTemp
;
1462 function getFilename() {
1463 return $this->filename
;
1469 function getArchiveName() {
1470 return $this->archiveName
;
1476 function getSize() {
1483 function getType() {
1490 function getAction() {
1491 return $this->action
;
1497 function getParams() {
1498 return $this->params
;
1504 function importOldRevision() {
1505 $dbw = wfGetDB( DB_MASTER
);
1507 # Sneak a single revision into place
1508 $user = User
::newFromName( $this->getUser() );
1510 $userId = intval( $user->getId() );
1511 $userText = $user->getName();
1515 $userText = $this->getUser();
1516 $userObj = new User
;
1519 // avoid memory leak...?
1520 $linkCache = LinkCache
::singleton();
1521 $linkCache->clear();
1523 $page = WikiPage
::factory( $this->title
);
1524 $page->loadPageData( 'fromdbmaster' );
1525 if ( !$page->exists() ) {
1526 # must create the page...
1527 $pageId = $page->insertOn( $dbw );
1529 $oldcountable = null;
1531 $pageId = $page->getId();
1534 $prior = $dbw->selectField( 'revision', '1',
1535 array( 'rev_page' => $pageId,
1536 'rev_timestamp' => $dbw->timestamp( $this->timestamp
),
1537 'rev_user_text' => $userText,
1538 'rev_comment' => $this->getComment() ),
1542 // @todo FIXME: This could fail slightly for multiple matches :P
1543 wfDebug( __METHOD__
. ": skipping existing revision for [[" .
1544 $this->title
->getPrefixedText() . "]], timestamp " . $this->timestamp
. "\n" );
1547 $oldcountable = $page->isCountable();
1550 # @todo FIXME: Use original rev_id optionally (better for backups)
1552 $revision = new Revision( array(
1553 'title' => $this->title
,
1555 'content_model' => $this->getModel(),
1556 'content_format' => $this->getFormat(),
1557 //XXX: just set 'content' => $this->getContent()?
1558 'text' => $this->getContent()->serialize( $this->getFormat() ),
1559 'comment' => $this->getComment(),
1561 'user_text' => $userText,
1562 'timestamp' => $this->timestamp
,
1563 'minor_edit' => $this->minor
,
1565 $revision->insertOn( $dbw );
1566 $changed = $page->updateIfNewerOn( $dbw, $revision );
1568 if ( $changed !== false && !$this->mNoUpdates
) {
1569 wfDebug( __METHOD__
. ": running updates\n" );
1570 $page->doEditUpdates(
1573 array( 'created' => $created, 'oldcountable' => $oldcountable )
1580 function importLogItem() {
1581 $dbw = wfGetDB( DB_MASTER
);
1582 # @todo FIXME: This will not record autoblocks
1583 if ( !$this->getTitle() ) {
1584 wfDebug( __METHOD__
. ": skipping invalid {$this->type}/{$this->action} log time, timestamp " .
1585 $this->timestamp
. "\n" );
1588 # Check if it exists already
1589 // @todo FIXME: Use original log ID (better for backups)
1590 $prior = $dbw->selectField( 'logging', '1',
1591 array( 'log_type' => $this->getType(),
1592 'log_action' => $this->getAction(),
1593 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1594 'log_namespace' => $this->getTitle()->getNamespace(),
1595 'log_title' => $this->getTitle()->getDBkey(),
1596 'log_comment' => $this->getComment(),
1597 #'log_user_text' => $this->user_text,
1598 'log_params' => $this->params
),
1601 // @todo FIXME: This could fail slightly for multiple matches :P
1604 . ": skipping existing item for Log:{$this->type}/{$this->action}, timestamp "
1605 . $this->timestamp
. "\n" );
1608 $log_id = $dbw->nextSequenceValue( 'logging_log_id_seq' );
1610 'log_id' => $log_id,
1611 'log_type' => $this->type
,
1612 'log_action' => $this->action
,
1613 'log_timestamp' => $dbw->timestamp( $this->timestamp
),
1614 'log_user' => User
::idFromName( $this->user_text
),
1615 #'log_user_text' => $this->user_text,
1616 'log_namespace' => $this->getTitle()->getNamespace(),
1617 'log_title' => $this->getTitle()->getDBkey(),
1618 'log_comment' => $this->getComment(),
1619 'log_params' => $this->params
1621 $dbw->insert( 'logging', $data, __METHOD__
);
1627 function importUpload() {
1629 $archiveName = $this->getArchiveName();
1630 if ( $archiveName ) {
1631 wfDebug( __METHOD__
. "Importing archived file as $archiveName\n" );
1632 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1633 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1635 $file = wfLocalFile( $this->getTitle() );
1636 wfDebug( __METHOD__
. 'Importing new file as ' . $file->getName() . "\n" );
1637 if ( $file->exists() && $file->getTimestamp() > $this->getTimestamp() ) {
1638 $archiveName = $file->getTimestamp() . '!' . $file->getName();
1639 $file = OldLocalFile
::newFromArchiveName( $this->getTitle(),
1640 RepoGroup
::singleton()->getLocalRepo(), $archiveName );
1641 wfDebug( __METHOD__
. "File already exists; importing as $archiveName\n" );
1645 wfDebug( __METHOD__
. ': Bad file for ' . $this->getTitle() . "\n" );
1649 # Get the file source or download if necessary
1650 $source = $this->getFileSrc();
1651 $flags = $this->isTempSrc() ? File
::DELETE_SOURCE
: 0;
1653 $source = $this->downloadSource();
1654 $flags |
= File
::DELETE_SOURCE
;
1657 wfDebug( __METHOD__
. ": Could not fetch remote file.\n" );
1660 $sha1 = $this->getSha1();
1661 if ( $sha1 && ( $sha1 !== sha1_file( $source ) ) ) {
1662 if ( $flags & File
::DELETE_SOURCE
) {
1663 # Broken file; delete it if it is a temporary file
1666 wfDebug( __METHOD__
. ": Corrupt file $source.\n" );
1670 $user = User
::newFromName( $this->user_text
);
1672 # Do the actual upload
1673 if ( $archiveName ) {
1674 $status = $file->uploadOld( $source, $archiveName,
1675 $this->getTimestamp(), $this->getComment(), $user, $flags );
1677 $status = $file->upload( $source, $this->getComment(), $this->getComment(),
1678 $flags, false, $this->getTimestamp(), $user );
1681 if ( $status->isGood() ) {
1682 wfDebug( __METHOD__
. ": Successful\n" );
1685 wfDebug( __METHOD__
. ': failed: ' . $status->getHTML() . "\n" );
1691 * @return bool|string
1693 function downloadSource() {
1694 if ( !$this->config
->get( 'EnableUploads' ) ) {
1698 $tempo = tempnam( wfTempDir(), 'download' );
1699 $f = fopen( $tempo, 'wb' );
1701 wfDebug( "IMPORT: couldn't write to temp file $tempo\n" );
1706 $src = $this->getSrc();
1707 $data = Http
::get( $src );
1709 wfDebug( "IMPORT: couldn't fetch source $src\n" );
1715 fwrite( $f, $data );
1724 * Source interface for XML import.
1726 interface ImportSource
{
1729 * Indicates whether the end of the input has been reached.
1730 * Will return true after a finite number of calls to readChunk.
1732 * @return bool true if there is no more input, false otherwise.
1737 * Return a chunk of the input, as a (possibly empty) string.
1738 * When the end of input is reached, readChunk() returns false.
1739 * If atEnd() returns false, readChunk() will return a string.
1740 * If atEnd() returns true, readChunk() will return false.
1742 * @return bool|string
1744 function readChunk();
1748 * Used for importing XML dumps where the content of the dump is in a string.
1749 * This class is ineffecient, and should only be used for small dumps.
1750 * For larger dumps, ImportStreamSource should be used instead.
1752 * @ingroup SpecialPage
1754 class ImportStringSource
implements ImportSource
{
1755 function __construct( $string ) {
1756 $this->mString
= $string;
1757 $this->mRead
= false;
1764 return $this->mRead
;
1768 * @return bool|string
1770 function readChunk() {
1771 if ( $this->atEnd() ) {
1774 $this->mRead
= true;
1775 return $this->mString
;
1780 * Imports a XML dump from a file (either from file upload, files on disk, or HTTP)
1781 * @ingroup SpecialPage
1783 class ImportStreamSource
implements ImportSource
{
1784 function __construct( $handle ) {
1785 $this->mHandle
= $handle;
1792 return feof( $this->mHandle
);
1798 function readChunk() {
1799 return fread( $this->mHandle
, 32768 );
1803 * @param string $filename
1806 static function newFromFile( $filename ) {
1807 wfSuppressWarnings();
1808 $file = fopen( $filename, 'rt' );
1809 wfRestoreWarnings();
1811 return Status
::newFatal( "importcantopen" );
1813 return Status
::newGood( new ImportStreamSource( $file ) );
1817 * @param string $fieldname
1820 static function newFromUpload( $fieldname = "xmlimport" ) {
1821 $upload =& $_FILES[$fieldname];
1823 if ( $upload === null ||
!$upload['name'] ) {
1824 return Status
::newFatal( 'importnofile' );
1826 if ( !empty( $upload['error'] ) ) {
1827 switch ( $upload['error'] ) {
1829 # The uploaded file exceeds the upload_max_filesize directive in php.ini.
1830 return Status
::newFatal( 'importuploaderrorsize' );
1832 # The uploaded file exceeds the MAX_FILE_SIZE directive that
1833 # was specified in the HTML form.
1834 return Status
::newFatal( 'importuploaderrorsize' );
1836 # The uploaded file was only partially uploaded
1837 return Status
::newFatal( 'importuploaderrorpartial' );
1839 # Missing a temporary folder.
1840 return Status
::newFatal( 'importuploaderrortemp' );
1841 # case else: # Currently impossible
1845 $fname = $upload['tmp_name'];
1846 if ( is_uploaded_file( $fname ) ) {
1847 return ImportStreamSource
::newFromFile( $fname );
1849 return Status
::newFatal( 'importnofile' );
1854 * @param string $url
1855 * @param string $method
1858 static function newFromURL( $url, $method = 'GET' ) {
1859 wfDebug( __METHOD__
. ": opening $url\n" );
1860 # Use the standard HTTP fetch function; it times out
1861 # quicker and sorts out user-agent problems which might
1862 # otherwise prevent importing from large sites, such
1863 # as the Wikimedia cluster, etc.
1864 $data = Http
::request( $method, $url, array( 'followRedirects' => true ) );
1865 if ( $data !== false ) {
1867 fwrite( $file, $data );
1870 return Status
::newGood( new ImportStreamSource( $file ) );
1872 return Status
::newFatal( 'importcantopen' );
1877 * @param string $interwiki
1878 * @param string $page
1879 * @param bool $history
1880 * @param bool $templates
1881 * @param int $pageLinkDepth
1884 public static function newFromInterwiki( $interwiki, $page, $history = false,
1885 $templates = false, $pageLinkDepth = 0
1887 if ( $page == '' ) {
1888 return Status
::newFatal( 'import-noarticle' );
1890 $link = Title
::newFromText( "$interwiki:Special:Export/$page" );
1891 if ( is_null( $link ) ||
!$link->isExternal() ) {
1892 return Status
::newFatal( 'importbadinterwiki' );
1896 $params['history'] = 1;
1899 $params['templates'] = 1;
1901 if ( $pageLinkDepth ) {
1902 $params['pagelink-depth'] = $pageLinkDepth;
1904 $url = $link->getFullURL( $params );
1905 # For interwikis, use POST to avoid redirects.
1906 return ImportStreamSource
::newFromURL( $url, "POST" );